package com.yihu.wlyy.service.app.hospital;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.repository.TownDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.yihu.wlyy.entity.address.Hospital;
import com.yihu.wlyy.repository.HospitalDao;
import com.yihu.wlyy.service.BaseService;

@Component
@Transactional(rollbackFor = Exception.class)
public class HospitalService extends BaseService {

	@Autowired
	private HospitalDao hospitalDao;
	@Autowired
	private TownDao townDao;

	/**
	 * 获取医院列表
	 * @param query 查询条件 ：医院名称
	 * @param id 
	 * @return
	 */
	public Page<Hospital> getHospitalList(String query, int type, long id, int pageSize) {
		if (pageSize <= 0) {
			pageSize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pageSize, sort);
		// 查询全部
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		if (StringUtils.isNotEmpty(query)) {
			filters.put("name", new SearchFilter("name", Operator.LIKE, query));
		}
		//只能找社区签约
		filters.put("level", new SearchFilter("level", Operator.EQ,2));
		//排除站点
		filters.put("centerSite", new SearchFilter("centerSite", Operator.EQ,"00"));
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}
		// 未作废
		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
		Specification<Hospital> spec = DynamicSpecifications.bySearchFilter(filters.values(), Hospital.class);
		return hospitalDao.findAll(spec, pageRequest);
	}

	public List<Town> getTownByCityCode(String city) {
		return townDao.findByCityCode(city);
	}

	public List<Hospital> getHositalByTownCode(String town) {
		return hospitalDao.findByTownCode(town);
	}
}
